#include "thread_pool.h"

void thread_pool::worker_thread()
{
    while(!_done)
    {
        function<void()> task;
        if(_work_queue.try_pop())
        {
            task(); // 执行
        }
        else
        {
            std::this_thread::yield(); //无任务被取出 让出cpu
        }
    }
}
thread_pool::thread_pool(size_t thread_num)
: _done(false)
// , _thread_num(thread_num)
, _joiner(_threads)
{
    const size_t thread_cnt = thread::hardware_concurrency();
    _thread_num = thread_num > 0 ? thread_num : thread_cnt;
    try
    {
        for(size_t i = 0; i < _thread_num; ++i)
        {
            _threads.push_back(thread(&thread_pool::worker_thread, this));
        }
    } 
    catch (...)
    {
        _done = true;
        throw;
    }
}
thread_pool::~thread_pool()
{
    _done = true;
}